#!/bin/zsh
clear

######################################################################################
##
## This script uses FLIF to optimize PNG files, it saves some time.
## Expects 1 arg, that being the desired file to optimize.
##
######################################################################################

PNG_IN=$1
PNG_IN_NAME=$(echo "$1" | rev | cut -d '.' -f2 | cut -d '/' -f1 | rev)
PNG_IN_8BYTE_HEADER=$(xxd -p "$1" | head -c 8)

clean()
{
    rm -rf ~/imgopt/tmp/
}

check_dependencies()
{
######################################################################################
##
## Brew and FLIF are needed, you are given the option to install.
##
######################################################################################

    echo -e "[-] Dependencies needed: $DID_NOT_FIND\n"
    echo "> Would you like to install?"

    read -r USER_SELECTED_INSTALL

    case "$USER_SELECTED_INSTALL" in

        Y | YES | y | yes) install_deps
		    ;;
        *) exit
    esac
}

init()
{
    mkdir -p ~/imgopt/tmp/
    mkdir -p ~/imgopt/log/
}

install_deps()
{

######################################################################################
##
## Must be a priv. user to perform installations.
##
######################################################################################

    BREWTEST=$(command -v brew)
    FLIFTEST=$(command -v flif)
    
    if [[ "$BREWTEST" == "brew not found" ]]
    then    
        if [[ $(id -un) != root || $(id -Gn) != *admin* ]]
        then
            sudo /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
        else
            echo "[-] Must be root or admin to install Homebrew"
            exit
        fi
    else
        if [[ "$FLIFTEST" == "flif not found" ]]
        then
            if [[ $(id -un) == root || $(id -Gn) == *admin* ]]
            then
            	brew install flif
            else          
                echo "[-] Must be root or admin to install FLIF"
            fi
        else
            :
        fi			
    fi
}

timestamp()
{

######################################################################################
##
## Generates date to log this instance into the log file.
##
######################################################################################

    printf '\n%s\n' '------------------------' >> ~/imgopt/log/log.txt
    date +'%Y-%m-%d | %r' >> ~/imgopt/log/log.txt
    printf '%s\n' '------------------------' >> ~/imgopt/log/log.txt
}


header_check()
{

######################################################################################
##
## Verifies PNG by matching first beginning bytes with expected PNG signature.
## This is probably stupid but let me feel clever.
## 
## PNG SIG INFO: http://www.libpng.org/pub/png/spec/1.2/PNG-Structure.html
##
######################################################################################

    if [ "$PNG_IN_8BYTE_HEADER" != "89504e47" ]
    then
        timestamp
        echo "ERROR: Input file was not a proper PNG" | tee -a ~/imgopt/log/log.txt
        exit
    else
        :
    fi
}

######################################################################################
##
## Main section 
##
######################################################################################

unset DID_NOT_FIND
	
if [ ! -f /usr/local/bin/brew ]
then    
    DID_NOT_FIND+=(brew)
else
    :
fi
	
if [ ! -f /usr/local/bin/flif ]
    then
        DID_NOT_FIND+=(FLIF)
else
    :
fi

if [ ! -z "$DID_NOT_FIND" ]
then
    check_dependencies
else
    :
fi

header_check
init
timestamp

######################################################################################
##
## Compare file size differences and print to screen.
##
######################################################################################

PNG_IN_SIZE=$(stat "$1" | cut -d ' ' -f1)


flif -v -E100 -N -Q75 "$PNG_IN" ~/imgopt/tmp/"$PNG_IN_NAME".flif \
    | tee -a ~/imgopt/log/log.txt
flif -v -q100 ~/imgopt/tmp/"$PNG_IN_NAME".flif ~/imgopt/"$PNG_IN_NAME"-imgopt.png \
    | tee -a ~/imgopt/log/log.txt
clear

if [ -f /Users/"$USER"/imgopt/"$PNG_IN_NAME"-imgopt.png ]
then
    PNG_IN_SIZE=$(stat "$1" | cut -d ' ' -f8)
    PNG_OUT_SIZE=$(stat /Users/"$USER"/imgopt/"$PNG_IN_NAME"-imgopt.png | cut -d ' ' -f8)
    PNG_SIZE_DIFF=$(bc <<< "100 - $(bc <<< "$(bc <<< "scale=10; $PNG_OUT_SIZE / $PNG_IN_SIZE") * 100" | cut -b -5)")

    echo "> Original size: $PNG_IN_SIZE"
    echo "> New file size: $PNG_OUT_SIZE"
    echo "> Difference:    $PNG_SIZE_DIFF%"

    printf '\x0a\x0a'
    echo "> Saved to /Users/$USER/imgopt/$PNG_IN_NAME-imgopt.png"
    printf '\x0a\x0a'
else
    echo "> ERROR saving file"
    echo "> Log: /Users/$USER/imgopt/log/log.txt"
    printf '\x0a\x0a'
fi

# Delete tmp directory

clean

open ~/imgopt/